import { Row, Col, Select, PageHeader, Input, Button, Table, Tag, Space, Form, Divider, Popconfirm, message, Pagination } from "antd";
import { useEffect, useState } from "react";
import axios from "axios";
import { Link, useNavigate } from 'react-router-dom';


const { Option } = Select;

export default function Product() {
    const [form] = Form.useForm();
    const [dataSource, setDataSource] = useState([]);
    const [status, setStatus] = useState();
    const [totalCount, setTotalCount] = useState();
    const [pageCondition, setPageCondition] = useState({});
    const [currentPage, setCurrentPage] = useState();
    const [queryCondition, setQueryCondition] = useState({});
    const navigate = useNavigate();
    useEffect(() => {
        queryShop({}, {});
    }, []);

    function queryShop(queryCondition, pageCondition) {
        const instance = axios.create({
            headers: { "tenantId": 500, "userId": 11000 }
        })
        const request = {
            "name": queryCondition.name,
            "from": queryCondition.from,
            "to": queryCondition.to,
            "unitOfMeasure": queryCondition.unitOfMeasure,
            "enabled": queryCondition.enabled,
            "pageIndex": pageCondition.pageIndex,
            "pageSize": pageCondition.pageSize
        }
        instance.post('/product/search', request)
            .then((res) => {
                if (res.data.status.code === 0) {
                    setDataSource([res.data.data.records]);
                    setTotalCount(res.data.data.totalCount);
                    setCurrentPage(res.data.data.pageIndex);
                }
            })
    }

    const onFinish = (values) => {
        console.log(values);
        const queryCondition = {
            "name": values.productName,
            "from": values.from,
            "to": values.to,
            "unitOfMeasure": values.unitOfMeasure,
            "enabled": values.enabled
        }
        setQueryCondition(queryCondition);
        queryShop(queryCondition, pageCondition);
    }

    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };

    const onPageChange = (pageIndex, pageSize) => {
        const pageCondition = {
            "pageIndex": (pageIndex === 1) ? pageIndex : (pageIndex - 1) * 10,
            "pageSize": pageSize * pageIndex
        }
        setPageCondition(pageCondition);
        queryShop(queryCondition, pageCondition);
    }

    const closeOrOpenShop = (value) => {
        console.log(value)
        if (value.enabled) {
            const instance = axios.create({
                headers: { "tenantId": value.tenantId, "userId": value.auditing.createdBy }
            })
            instance.post('/product/' + value.id + '/disable', {
                "version": value.version
            })
                .then((res) => {
                    queryShop(queryCondition, pageCondition);
                })
            return;
        }
        const instance = axios.create({
            headers: { "tenantId": value.tenantId, "userId": value.auditing.createdBy }
        })
        instance.post('/product/' + value.id + '/enable', {
            "version": value.version
        })
            .then((res) => {
                queryShop(queryCondition, pageCondition);
            })
    };

    function confirm(e) {
        message.success('操作成功！');
        closeOrOpenShop(status);
    };

    function cancel(e) {
        console.log(e);
    };

    const onReset = () => {
        queryShop({}, {});
    }

    const columns = [
        {
            title: '状态',
            dataIndex: 'enabled',
            key: 'enabled',
            render: enabled => <Tag>{enabled ? '已上架' : '已下架'}</Tag>,
        },
        {
            title: '菜品名',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '菜品单价（元）',
            dataIndex: 'unitPrice',
            key: 'unitPrice',
        },
        {
            title: '计量单位',
            key: 'unitOfMeasure',
            dataIndex: 'unitOfMeasure',
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <>
                    <Space size="middle">
                        <Button
                            className="edit-btn"
                            onClick={() => {
                                navigate('/editProduct', { state: { data: text }, replace: true });
                                console.log(text)
                            }}>
                            编辑
                        </Button>|
                        <Popconfirm
                            title={text.enabled ? "请确认是否需要下架该菜品？" : "请确认是否需要上架该菜品？"}
                            onConfirm={confirm}
                            onCancel={cancel}
                            okText="是"
                            cancelText="否"
                        >
                            <Button
                                className="edit-btn"
                                onClick={() => {
                                    setStatus(text);
                                }}
                            >
                                {text.enabled ? "下架" : "上架"}
                            </Button>
                        </Popconfirm>
                    </Space>
                </>
            ),
        },
    ];

    return (
        <>
            <Row className="title-row" >
                <Col span={18}>
                    <PageHeader
                        className="site-page-header"
                        title="菜品管理"
                        subTitle=""
                    />
                </Col>
            </Row>
            <Form
                form={form}
                name="searchCondition"
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
                initialValues={{ remember: true }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                autoComplete="off"
            >
                <Row gutter={[16, 12]}>
                    <Col style={{ "width": "32px" }}>
                        <Divider><span className="span-shop-address">营业状态</span></Divider>
                    </Col>
                    <Col span={6}>
                        <Form.Item
                            name="enabled"
                        >
                            <Select
                                defaultValue="所有"
                                style={{
                                    "width": "180px",
                                    "marginLeft": "81px",
                                    "borderLeft": "none"
                                }}
                            >
                                <Option>所有</Option>
                                <Option value="true">已上架</Option>
                                <Option value="false">已下架</Option>
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col style={{ "width": "32px" }}>
                        <Divider><span className="span-shop-address">菜品单价</span></Divider>
                    </Col>
                    <Col span={6}>
                        <Form.Item
                            name="from"
                        >
                            <Input className="from" style={{ width: 80 }} />
                        </Form.Item>
                    </Col>
                    <Col>
                        <span className="wave">~</span>
                    </Col>
                    <Col>
                        <Form.Item
                            name="to"
                        >
                            <Input className="to" placeholder="元" style={{ width: 80 }} />
                        </Form.Item>
                    </Col>
                    <Col style={{ "width": "32px" }}>
                        <Divider><span className="span-shop-address">计量单位</span></Divider>
                    </Col>
                    <Col span={8}>
                        <Form.Item
                            name="unitOfMeasure"
                        >
                            <Input style={{ width: 135 }} />
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col style={{ "width": "32px" }}>
                        <Divider><span className="span-shop-address">菜品名</span></Divider>
                    </Col>
                    <Col span={6}>
                        <Form.Item
                            name="productName"
                        >
                            <Input
                                className="productName"
                                placeholder="菜品名"
                                style={{ width: 280 }}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item
                        >
                            <Button
                                htmlType="submit"
                                style={{
                                    "backgroundColor": "rgb(244,188,72)",
                                    "width": "160px"
                                }}
                            >
                                查询
                            </Button>
                        </Form.Item>
                    </Col>
                    <Col span={4}>
                        <Form.Item
                        >
                            <Button
                                htmlType="reset"
                                onClick={onReset}
                            >
                                重置
                            </Button>
                        </Form.Item>
                    </Col>
                    <Col span={4}>
                        <Button>
                            <Link to={'/createProduct'}>创建新菜品</Link>
                        </Button>
                    </Col>
                </Row>
                <Row>
                    <Col span={24}>
                        <Table
                            columns={columns}
                            dataSource={dataSource[0]}
                            scroll={{ y: '350px' }}
                            pagination={false}
                        />
                    </Col>

                    <Pagination
                        total={totalCount}
                        current={currentPage}
                        showQuickJumper
                        showSizeChanger
                        style={{
                            "marginTop": "10px"
                        }}
                        onChange={onPageChange}
                    />
                </Row>
            </Form>
        </>
    );
}